package nvshens;

import java.io.IOException;
import java.net.URL;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang3.StringUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import nvshens.bean.NsSingle;

public class Single {
	// 元素ID|该图集包含70张照片
	private static final String id_single_page_num = "dinfo";
	// <ul id="hgallery"><img
	// src="https://img.onvshen.com:85/gallery/22162/32819/s/0.jpg" alt="[XIUREN]
	// 2020.05.13 杨晨晨sugar_0"
	public static final String id_single_page_url = "hgallery";

	public static final String testImgUrl = "https://img.onvshen.com:85/gallery/22162/32819/s/0.jpg";

	// 图片名是 005.jpg|是三位数字，不够补充0
	public static final String num_format = "%03d";

	private static final String basePah = "/nvshens/";

	private static String savePath = "/";

	private static ExecutorService pool = Executors.newFixedThreadPool(8);

	public static void main(String[] args) throws IOException {

		savePath = getPath();
		NsSingle nsSingle = new NsSingle();
		parse(nsSingle, args[0]);
		pool.submit(new NsRunnable(nsSingle, StringUtils.join(savePath, basePah)));
		System.out.println("finishel");
	}

	/**
	 * 下载详情页 https://www.nvshens.org/g/33205/
	 *
	 * @param bean
	 * @param pageUrl
	 * @throws IOException
	 */
	static void parse(NsSingle bean, String pageUrl) throws IOException {
		Document root = Jsoup.connect(pageUrl).timeout((int) TimeUnit.SECONDS.toMillis(50)).get();
		Elements numSpan = root.getElementById(id_single_page_num).getElementsByTag("span");
		bean.setNum(Integer.parseInt(StringUtils.getDigits(numSpan.text())));

		bean.setPageUrl(pageUrl);

		Element eleOfImg = root.getElementById(id_single_page_url).getAllElements().get(0);
		String imgSrc = eleOfImg.child(0).attr("src");

		bean.setExtName(StringUtils.join(".", FilenameUtils.getExtension(imgSrc)));
		bean.setPicUrl(StringUtils.join(FilenameUtils.getFullPath(imgSrc), num_format, ".", FilenameUtils.getExtension(imgSrc)));
		if (pageUrl.endsWith("/")) {
			// 为了去除最后一个空格，从而提起名字
			pageUrl = StringUtils.substring(pageUrl, 0, pageUrl.length() - 1);
		}
		bean.setSavePath(FilenameUtils.getBaseName(pageUrl));
	}

	public static String getPath() {
		System.err.println("******************************************");
		Thread currentThread = Thread.currentThread();
		URL resource3 = currentThread.getContextClassLoader().getResource("");
		URL resource = currentThread.getClass().getResource("/");
		System.out.println(resource.getPath().toString());
	
		return resource.getPath().toString();
	}
	
}
